<template>
  <a-card :bordered="false">
    <search :config="searchConfig" @search="search" @getHeight="getHeight"/>
    <div class="page_table">
      <vxe-grid
        ref="xGrid"
        :border="true"
        :resizable="true"
        :showOverflow="true"
        size="mini"
        :loading="loading"
        :height="pageHeight-seachHeight-94"
        :align="left"
        :columns="columns"
        :data="dataSource"
        :toolbar-config="tableToolbar"
        :checkbox-config="checkboxConfig"
        v-bind="vexConfig"
        @checkbox-change="selectChangeEvent"
        @checkbox-all="selectChangeEvent"
      >
        <template #toolbar_buttons>
          <div class="table-operator">
            <a-button v-has="'dealer:add'" @click="handleAdd">新增</a-button>
            <a-button v-has="'dealer:delete'" @click="batchDel">删除</a-button>
            <a-button type="primary" @click="handleExportXls('经销商管理')">模板下载</a-button>
            <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader1"
                      :action="importExcelUrl" @change="handleImportExcel">
              <a-button type="primary" >导入</a-button>
            </a-upload>
            <a-button type='primary' v-has="'dealer:export'" @click="downExportXls('customer_service')">导出</a-button>
          </div>
        </template>

        <template #detail="{ row,rowIndex }">
          <a @click="handleDetail(row)">{{ row.custCode }}</a>
        </template>
        <template #isGroupPurchase="{ row,rowIndex }">
          {{ row.isGroupPurchase == 1 ? '是' : '否' }}
        </template>
        <template #isTransportMerchants="{ row,rowIndex }">
          {{ row.isTransportMerchants == 1 ? '是' : '否' }}
        </template>
        <template #action="{ row,rowIndex }">
          <a v-has="'dealer:update'" @click="handleEdit(row)">编辑</a>
          <a-divider type="vertical"/>
          <a-dropdown>
            <a class="ant-dropdown-link">
              更多
              <a-icon type="down"/>
            </a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a href='javascript:' @click="handleConfig(row)">客户配置</a>
              </a-menu-item>
<!--              <a-menu-item>-->
<!--                <a href='javascript:' @click="handleConfigTer(row)">商品配置</a>-->
<!--              </a-menu-item>-->
              <a-menu-item v-has="'business:log'">
                <a href='javascript:' @click='handleBusiness("经销商信息",row)'>日志</a>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </template>

        <template #update="{ row }">
          <a-switch :checked="row.status" size="small" @change="handleStatus(row,$event,)"/>
        </template>
        <template #pager>
          <vxe-pager
            :layouts="['Total', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump','Sizes', 'FullJump']"
            :currentPage.sync="ipagination.current"
            :page-size.sync="ipagination.pageSize"
            :total="ipagination.total"
            :pageSizes="ipagination.pageSizeOptions"
            @page-change="handlePageChange">
          </vxe-pager>
        </template>
      </vxe-grid>
    </div>
    <!-- 操作按钮区域 -->

    <!-- table区域-begin -->

    <!--     table区域-end -->
    <business-log ref="businessLog"></business-log>
    <!-- 表单区域 -->
    <dealer-modal ref="modalForm" @ok="modalFormOk"></dealer-modal>

    <enterprise-config-modal ref="ConfigModal" @ok="saveUserRelation"></enterprise-config-modal>
    <!--    商品配置-->
    <commodity-configuration ref='ConfigTer' @ok="commodity"></commodity-configuration>
  </a-card>
</template>

<script>
import WhiteModal from '../terminal/modules/WhiteModal'
import { postAction, getFileAccessHttpUrl, getAction } from '@/api/manage'
import dealerModal from './modules/dealerModal'
import stockModal from '../terminal/modules/stockModal'
import JSuperQuery from '@/components/cn-form/JSuperQuery.vue'
import JInput from '@/components/cn-form/JInput.vue'
import uploadExcel from '@/components/upload-file/UploadExcel.vue'
import { initDictOptions, filterDictText, filterDictTextByCache } from '@/components/dict/CnDictSelectUtil'
import { PageListMixin } from '@/mixins/PageListMixin'
import Vue from 'vue'
import { filterObj } from '@/utils/util'
import JTreeSelect from '@/components/cn-form/JTreeSelect'
import EnterpriseConfigModal from './modules/EnterpriseConfigModal'
import CommodityConfiguration from './modules/CommodityConfiguration'
import { ACCESS_TOKEN } from '@/store/mutation-types'

export default {
  name: 'terminal-list',
  mixins: [PageListMixin],
  components: {
    uploadExcel,
    dealerModal,
    stockModal,
    JSuperQuery,
    JInput,
    JTreeSelect,
    WhiteModal,
    EnterpriseConfigModal,
    CommodityConfiguration
  },
  data() {
    return {
      tokenHeader1: {'Authorization':  'Bearer ' + Vue.ls.get(ACCESS_TOKEN).access_token},
      state:false,
      custCode:'',
      terminals:'',
      description: '单表示例列表',
      searchConfig: [
        {
          type: 'input',
          name: 'custCode',
          placeholder: '客户编号'
        },
        {
          type: 'input',
          name: 'custName',
          placeholder: '客户名称'
        },
        {
          type: 'tree-select',
          dataType: 'org',
          name: 'departCode',
          placeholder: '所属组织'
        },
        {
          type: 'j-select',
          dictCode: 'cust_type',
          name: 'custType',
          placeholder: '客户类型'
        },
      ],
      //字典数组缓存
      sexDictOptions: [],
      importExcelUrl: `${window._CONFIG['domianURL']}/customerController/importExcel`,
      //列设置
      settingColumns: [],
      //列定义
      columns: [
        { type: 'checkbox', width: 60, fixed: 'left' },
        {
          title: '客户编码',
          field: 'custCode',
          minWidth: 100,
          fixed: 'left',
          slots: { default: 'detail' }
        },
        {
          title: '客户名称',
          align: 'left',
          minWidth: 80,
          field: 'custName'
        },
        {
          title: '客户类型',
          align: 'left',
          minWidth: 80,
          field: 'custTypeStr'
        },
        {
          title: '所属组织',
          align: 'left',
          minWidth: 80,
          field: 'departName'
        },
        {
          title: '联系人',
          align: 'left',
          minWidth: 80,
          field: 'linkman'
        },
        {
          title: '联系电话',
          align: 'left',
          minWidth: 80,
          field: 'telephone'
        },
        {
          title: '关联职位',
          align: 'left',
          minWidth: 80,
          field: 'associatedPosition',
          ellipsis: true
        },
        {
          title: '创建人',
          align: 'left',
          minWidth: 80,
          field: 'createName'
        },
        {
          title: '创建时间',
          minWidth: 140,
          field: 'createTime'
        },
        {
          title: '更新人',
          align: 'left',
          minWidth: 80,
          field: 'updateName'
        },
        {
          title: '更新时间',
          align: 'left',
          minWidth: 80,
          field: 'updateTime'
        },
        {
          title: '状态',
          align: 'left',
          field: 'status',
          width: 60,
          fixed: 'right',
          minWidth: 80,
          slots: { default: 'update' }
        },
        {
          title: '操作',
          width: 150,
          align: 'left',
          fixed: 'right',
          slots: { default: 'action' }
        }
      ],
      isorter: {
        permflag: 'customer_page_impl'
      },
      manner: [],
      url: {
        list: window._CONFIG['domianURL'] + '/customerController/getPageList',
        delete: window._CONFIG['domianURL'] + '/customerController/deleteByid',
        detail: window._CONFIG['domianURL'] + '/customerController/getCnCustomerByIdOrCustCode',
        deleteBatch: '/customerController/deleteBatch',
        exportXlsUrl: '/customerController/exportXls',
        startOrStopUrl: window._CONFIG['domianURL'] + '/customerController/updateStatus',
        saveUserRelation: window._CONFIG['domianURL'] + '/customerExtendController/saveExtendPos',
        commodity: window._CONFIG['domianURL'] + '/cnCustomerProductController/saveCustomerProduct',
      },
      currentWhite: {}
    }
  },
  created() {
  },
  methods: {
    handleConfig(record, type, modal = 'ConfigModal') {
      this.$refs[modal].showModal(record)
      return false
    },
    handleConfigTer(record, type, modal = 'ConfigTer') {
      this.$refs[modal].showModal(record)
      return false
    },
    saveUserRelation(params) {
      postAction(this.url.saveUserRelation, params).then(async (res) => {
        if (res.success) {
          this.$message.success(res.message)
          await this.loadData()
          this.$refs.ConfigModal.close()
        } else {
          this.$message.warning(res.message)
        }
      }).finally(() => {
        this.$refs.ConfigModal.confirmLoading = false
        //that.close();
      })
      console.log(this.terminals)
    },
    commodity(params){
      console.log(params)
      postAction(this.url.commodity, params).then(async (res) => {
        if (res.success) {
          this.$message.success(res.message)
          await this.loadData()
          this.$refs.ConfigTer.close()
        } else {
          this.$message.warning(res.message)
        }
      }).finally(() => {
        this.$refs.ConfigTer.confirmLoading = false
        //that.close();
      })
      console.log(this.terminals)
    },
    filterDictText,
    getAvatarView: function (avatar) {
      return getFileAccessHttpUrl(avatar)
    },
    async handleWhite(record) {
      this.currentWhite = record
      this.$refs.WhiteModal.showModal(record.terminalCode)
    },
    handelSaveWhite(typeList, productList, positionList, record) {
      let that = this
      const tList = typeList.map(type => Object.assign({
        code: type.code,
        name: type.name,
        dataType: 3
      }))
      const pList = productList.map(type => Object.assign({
        code: type.code,
        name: type.name,
        remarks: type.imgUrl,
        dataType: 4
      }))
      const positions = positionList.map(type => Object.assign({
        code: type.positionCode,
        name: type.positionName,
        dataType: 5
      }))
      if (!record.extendVos) record.extendVos = []
      const retainRows = record.extendVos.filter(row => [1, 2].includes(Number(row.dataType)))
      record.extendVos = [...retainRows, ...tList, ...pList, ...positions]
      that.loadData()
      postAction(window._CONFIG['domianURL'] + '/cnTerminalController/saveTerExtend', record).then(async (res) => {
        if (res.success) {
          that.$message.success(res.message)
          this.$refs.WhiteModal.showModal('')
          this.$refs.WhiteModal.close()
        } else {
          this.$message.warning(res.message)
        }
      }).finally(() => {
        this.$refs.WhiteModal.confirmLoading = false
        //that.close();
      })
    },
    async handleStock(record) {
      const modal = this.$refs.stockModalForm
      modal.edit(record)
      modal.title = '详情'
      modal.disableSubmit = true
      return true
    },
    getQueryParams() {
      //高级查询器
      let sqp = {}
      if (this.superQueryParams) {
        sqp['superQueryParams'] = encodeURI(this.superQueryParams)
        sqp['superQueryMatchType'] = this.superQueryMatchType
      }
      var param = Object.assign(sqp, this.queryParam, this.isorter, this.filters)

      param.field = this.getQueryField()
      param.current = this.ipagination.current
      param.size = this.ipagination.pageSize
      delete param.birthdayRange //范围参数不传递后台
      return filterObj(param)
    },
    initDictConfig() {
      console.log('--我才是真的方法!--')
      initDictOptions('cpt_manner').then((res) => {
        if (res.success) {
          this.manner = res.result
        }
      })
    },
    //跳转单据页面
    jump() {
      this.$notification.success('跳转 ： jump')
    },
    onBirthdayChange: function (value, dateString) {
      console.log(dateString[0], dateString[1])
      this.queryParam.birthday_begin = dateString[0]
      this.queryParam.birthday_end = dateString[1]
    },
    //列设置更改事件
    onColSettingsChange(checkedValues) {
      var key = this.$route.name + ':colsettings'
      Vue.ls.set(key, checkedValues, 7 * 24 * 60 * 60 * 1000)
      this.settingColumns = checkedValues
      const cols = this.defColumns.filter(item => {
        if (item.key == 'rowIndex' || item.dataIndex == 'action') {
          return true
        }
        if (this.settingColumns.includes(item.dataIndex)) {
          return true
        }
        return false
      })
      this.columns = cols
    },
    initColumns() {
      //权限过滤（列权限控制时打开，修改第二个参数为授权码前缀）
      //this.defColumns = colAuthFilter(this.defColumns,'testdemo:');

      var key = this.$route.name + ':colsettings'
      let colSettings = Vue.ls.get(key)
      if (colSettings == null || colSettings == undefined) {
        let allSettingColumns = []
        this.defColumns.forEach(function (item, i, array) {
          allSettingColumns.push(item.dataIndex)
        })
        this.settingColumns = allSettingColumns
        this.columns = this.defColumns
      } else {
        this.settingColumns = colSettings
        const cols = this.defColumns.filter(item => {
          if (item.key == 'rowIndex' || item.dataIndex == 'action') {
            return true
          }
          if (colSettings.includes(item.dataIndex)) {
            return true
          }
          return false
        })
        this.columns = cols
      }
    },
    // 编辑

    // 上传

    handleUploadFile: function () {
      this.$refs.uploadFile.add()
      // this.$refs.uploadFile.title = "上传";
      this.$refs.uploadFile.disableSubmit = false
    }
  },

}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>
